package cn.xydpeng.springframework.core.io;

import cn.xydpeng.springframework.lang.Nullable;
import cn.xydpeng.springframework.util.Assert;
import cn.xydpeng.springframework.util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2022/10/14
 * @description:
 */
public class ClassPathResource extends AbstractResource {

    private final String path;

    private final String absolutePath;

    @Nullable
    private final ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
        Assert.notNull(path, "path must not null");
        //TODO 省略逻辑...
        String pathToUse = path;
        this.path = pathToUse;
        this.absolutePath = pathToUse;
        this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
    }


    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = this.classLoader.getResourceAsStream(this.path);
        if (is == null) {
            throw new FileNotFoundException(this.path+ ": cannot be opened because it does not exist");
        }
        return is;
    }


}
